//
//  XYUtils.m
//  PeiJue
//
//  Created by lxy on 2017/9/21.
//  Copyright © 2017年 lixiya. All rights reserved.
//

#import "XYUtils.h"
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <CoreLocation/CoreLocation.h>
#import <AVFoundation/AVFoundation.h>

@implementation XYUtils

+ (void)setUserDefault:(NSString *)key byValue:(id)value {
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)deleteUserDefault:(NSString *)key {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (id)getUserDefault:(NSString *)key {
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

+ (void)setInt:(NSInteger)i key:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:i forKey:key];
    [defaults synchronize];
}

+ (NSInteger)intForKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSInteger i=[defaults integerForKey:key];
    return i;
}

+ (void)setFloat:(CGFloat)floatValue key:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setFloat:floatValue forKey:key];
    [defaults synchronize];
}

+ (CGFloat)floatForKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    CGFloat floatValue=[defaults floatForKey:key];
    return floatValue;
}

+ (void)setBool:(BOOL)boolValue key:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:boolValue forKey:key];
    [defaults synchronize];
}

+ (BOOL)boolForKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL boolValue=[defaults boolForKey:key];
    return boolValue;
}

+(id) getObjectFromJsonString:(NSString *)jsonString {
    NSError *error = nil;
    if (jsonString) {
        id rev=[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUnicodeStringEncoding] options:NSJSONReadingMutableContainers error:&error];
        if (error==nil) {
            return rev;
        }else{
            return nil;
        }
    }
    return nil;
}

+ (NSString *)getJsonStringFromObject:(id)object {
    if ([NSJSONSerialization isValidJSONObject:object]){
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:0 error:nil];
        return [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return nil;
}


+ (NSArray *)getArrayFromPlist:(NSString *)plistName {
    NSString *path = [[NSBundle mainBundle] pathForResource:plistName
                                                     ofType:@"plist"];
    return [NSArray arrayWithContentsOfFile:path];
}


+ (NSString *)getDownloadFilePath:(NSString *)filename
{
    NSString *paths=[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    NSLog(@"paths____%@",paths);
    return ([paths stringByAppendingPathComponent:filename]);
}

#pragma mark - 删除本被文件
+ (void)removeFileAtPath:(NSString *)filePath {
    NSError *error = nil;
    if ([self isFileExitsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            NSLog(@"移除文件失败，错误信息：%@", error);
        }
        else {
            NSLog(@"成功移除文件");
        }
    }
    else {
        NSLog(@"文件不存在");
    }
}

+ (BOOL)isFileExitsAtPath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
        return YES;
    }
    return NO;
}

#pragma mark - 通常用于删除缓存的时，计算缓存大小
//单个文件的大小
+ (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
        
    }
    
    return 0;
}

//遍历文件夹获得文件夹大小，返回多少M
+ (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/(1024.0*1024.0);
}


#pragma mark -  NSDate互转NSString
+ (NSDate *)NSStringToDate:(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:dateString];
    return dateFromString;
}

+ (NSDate *)NSStringToDate:(NSString *)dateString withFormat:(NSString *)formatestr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatestr];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:dateString];
    return dateFromString;
}

+ (NSString *)NSDateToString:(NSDate *)dateFromString withFormat:(NSString *)formatestr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatestr];
    NSString *strDate = [dateFormatter stringFromDate:dateFromString];
    return strDate;
}

#pragma mark - 使用subString去除float后面无效的0
+ (NSString *)changeFloatWithString:(NSString *)stringFloat

{
    const char *floatChars = [stringFloat UTF8String];
    NSUInteger length = [stringFloat length];
    NSUInteger zeroLength = 0;
    NSInteger i = length-1;
    for(; i>=0; i--)
    {
        if(floatChars[i] == '0') {
            zeroLength++;
        } else {
            if(floatChars[i] == '.')
                i--;
            break;
        }
    }
    NSString *returnString;
    if(i == -1) {
        returnString = @"0";
    } else {
        returnString = [stringFloat substringToIndex:i+1];
    }
    return returnString;
}

#pragma mark - 去除float后面无效的0
+ (NSString *)changeFloatWithFloat:(CGFloat)floatValue

{
    return [self changeFloatWithString:[NSString stringWithFormat:@"%f",floatValue]];
}

#pragma mark - 如何通过一个整型的变量来控制数值保留的小数点位数。以往我们通类似@"%.2f"来指定保留2位小数位，现在我想通过一个变量来控制保留的位数
+ (NSString *)newFloat:(float)value withNumber:(int)numberOfPlace
{
    NSString *formatStr = @"%0.";
    formatStr = [formatStr stringByAppendingFormat:@"%df", numberOfPlace];
    NSLog(@"____%@",formatStr);
    
    formatStr = [NSString stringWithFormat:formatStr, value];
    NSLog(@"____%@",formatStr);
    
    printf("formatStr %s\n", [formatStr UTF8String]);
    return formatStr;
}


#pragma mark - 字符串类型判断
//..判断是否为整形：
+ (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形：
+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

+ (NSInteger)getSecondsWithBeginDate:(NSString*)currentDateString  AndEndDate:(NSString*)tomDateString{
    
    NSDate * currentDate = [XYUtils NSStringToDate:currentDateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSInteger currSec = [currentDate timeIntervalSince1970];
    
    NSDate *tomDate = [XYUtils NSStringToDate:tomDateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSInteger tomSec = [tomDate timeIntervalSince1970];
    
    NSInteger newSec = tomSec - currSec;
    NSLog(@"相差秒：%ld",(long)newSec);
    return newSec;
}


+ (BOOL)isValidateMobile:(NSString *)mobile{
    if([mobile isEqualToString:@""])
    {
        return NO;
    }
    NSString * phoneStr;
    if ([mobile rangeOfString:@"+"].location !=NSNotFound)
    {
        NSString *temp = [[NSMutableString stringWithString:mobile] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSMutableString * mTemp = [NSMutableString stringWithFormat:@"%@",temp];
        if ([mTemp hasPrefix:@"+86"])
        {
            [mTemp deleteCharactersInRange:NSMakeRange(3, 1)];
        }
        NSString *temp2 = [[NSMutableString stringWithString:mTemp] stringByReplacingOccurrencesOfString:@" " withString:@""];
        phoneStr = [[NSMutableString stringWithString:temp2] stringByReplacingOccurrencesOfString:@"+" withString:@""];
    }
    else
    {
        NSString *temp = [[NSMutableString stringWithString:mobile] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        phoneStr = [[NSMutableString stringWithString:temp] stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    //    NSString * phoneRegex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[012356789]|18[0-9]|14[012356789])[0-9]{8}$";
    //    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    return [phoneTest evaluateWithObject:phoneStr];
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[025-9]|9[0])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,17开头,180,189,181(增加),190(增加)
     22         */
    NSString * CT = @"^1((33|53|7[0-9]|8[019]|9[0])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:phoneStr]
         || [regextestcm evaluateWithObject:phoneStr]
         || [regextestct evaluateWithObject:phoneStr]
         || [regextestcu evaluateWithObject:phoneStr])) {
        return YES;
    }
    return NO;
}

//验证是否是邮箱
+ (BOOL)validateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    NSLog(@"%i",[emailTest evaluateWithObject:email]);
    return [emailTest evaluateWithObject:email];
}

//获取各种权限
+ (BOOL)handleWithAuthWith:(Authorization)Authorization{
    __block BOOL Autho = NO;
    
    //相机
    if (Authorization == AuthorizationTakePhoto){
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
            Autho = NO;
        } else {
            Autho = YES;
        }
    }
    //相册
    else if(Authorization == AuthorizationPhoto){
        ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
        if (status == kCLAuthorizationStatusDenied || kCLAuthorizationStatusRestricted) {
            Autho = NO;
        } else {
            Autho = YES;
        }
    }
    //定位
    else if(Authorization == AuthorizationLocation){
        //定位服务是否可用
        BOOL enable = [CLLocationManager locationServicesEnabled];
        //是否具有定位权限
        int status = [CLLocationManager authorizationStatus];
        if(!enable || status<3)
        {
            Autho = NO;
        }else{
            Autho = YES;
        }
    }else if(Authorization == AuthorizationAudio){
        //音频服务是否可用
        if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)]) {
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                if (granted) {
                    Autho = YES;
                }else{
                    Autho = NO;
                }
            }];
        }
    }
    return Autho;
}


#pragma mark - UIAlertController提示框
/** 在当前ViewController上弹出提示框 只有确定按钮*/
+ (void)showMessageWithViewController:(UIViewController *)vc title:(NSString *)title message:(NSString *)message confirmTitle:(NSString *)confirmTitle confirmHandler:(void(^)(UIAlertAction *action))confirmhandler {
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

    
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:confirmTitle ?: @"确定" style:UIAlertActionStyleDefault handler:confirmhandler];
    [alertC addAction:confirm];
    [vc presentViewController:alertC animated:YES completion:nil];
    
}

/** 在当前Window上弹出提示框 只有确定按钮*/
+ (void)showMessageWithTitle:(NSString *)title message:(NSString *)message confirmTitle:(NSString *)confirmTitle confirmHandler:(void(^)(UIAlertAction *action))confirmhandler{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *confirm = [UIAlertAction actionWithTitle:confirmTitle ?: @"确定" style:UIAlertActionStyleDefault handler:confirmhandler];
    [alertC addAction:confirm];

    [UIApplication.xy_topViewController presentViewController:alertC animated:YES completion:nil];
}

/** 在当前ViewController上弹出提示框 只有确定和取消按钮*/
+ (void)showMessageWithViewController:(UIViewController *)vc title:(NSString *)title message:(NSString *)message confirmTitle:(NSString *)confirmTitle cancleTitle:(NSString *)cancleTitle confirmHandler:(void(^)(UIAlertAction *action))confirmhandler cancleHandler:(void(^)(UIAlertAction *action))cancleHandler {
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:cancleTitle ?: @"取消" style:UIAlertActionStyleDefault handler:confirmhandler];
    [alertC addAction:cancle];

    UIAlertAction *confirm = [UIAlertAction actionWithTitle:confirmTitle ?: @"确定" style:UIAlertActionStyleDefault handler:confirmhandler];
    [alertC addAction:confirm];
    
    [vc presentViewController:alertC animated:YES completion:nil];
    
}

/** 在当前Window上弹出提示框 只有确定和取消按钮*/
+ (void)showMessageWithTitle:(NSString *)title message:(NSString *)message confirmTitle:(NSString *)confirmTitle cancleTitle:(NSString *)cancleTitle confirmHandler:(void(^)(UIAlertAction *action))confirmhandler cancleHandler:(void(^)(UIAlertAction *action))cancleHandler {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:cancleTitle ?: @"取消" style:UIAlertActionStyleDefault handler:confirmhandler];
    [alertC addAction:cancle];
    
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:confirmTitle ?: @"确定" style:UIAlertActionStyleDefault handler:confirmhandler];
    [alertC addAction:confirm];
    
    [UIApplication.xy_topViewController presentViewController:alertC animated:YES completion:nil];
}


@end
